package cn.bdqn.controller;

import cn.bdqn.utils.httputil.ResponseUtils;
import cn.bdqn.utils.httputil.Upload;
import com.baidu.ueditor.ActionEnter;
import com.sun.jersey.api.client.Client;
import org.apache.commons.io.FilenameUtils;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * baidu-ueditor
 * @author libo
 */
@RestController
@RequestMapping("/ueditor")

public class UEditorController {

    //后台图片保存地址
    private String ueditor = "file/ueditor/";

    //项目host路径
    private String uploadHost="http://localhost:8080/Studies_to_travel/";

    /**
     * ueditor文件上传（上传到外部服务器）
     * @param request
     * @param response
     * @param action
     */
    @RequestMapping(value="/ueditorUpload.do", method={RequestMethod.GET, RequestMethod.POST})
    public void editorUpload(HttpServletRequest request, HttpServletResponse response, String action) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println(action);
        System.out.println(ueditor);
        System.out.println(uploadHost);
        try {
            //如果是初始化
            if("config".equals(action)){
                String exec = new ActionEnter(request, rootPath).exec();
                PrintWriter writer = response.getWriter();
                writer.write(exec);
                writer.flush();
                writer.close();
                //如果是上传图片、视频、和其他文件
            }else if("uploadimage".equals(action) || "uploadvideo".equals(action) || "uploadfile".equals(action)){
                try {
                    System.out.println(request.getSession().getServletContext());
                    MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                    MultipartHttpServletRequest Murequest = resolver.resolveMultipart(request);
                    //得到文件map对象
                    Map<String, MultipartFile> files = Murequest.getFileMap();
                    // 实例化一个jersey
                    Client client = new Client();

                    for(MultipartFile pic: files.values()){
                        JSONObject jo = new JSONObject();
                        //文件大小
                        long size = pic.getSize();
                        //原来的文件名
                        String originalFilename = pic.getOriginalFilename();
                        String uploadInfo = Upload.upload(client, pic, request, response, uploadHost, ueditor);
                        //如果上传成功
                        if(!"".equals(uploadInfo)){
                            System.out.println("成功");
                            String[] infoList = uploadInfo.split(";");
                            jo.put("state", "SUCCESS");
                            //原来的文件名
                            jo.put("original", originalFilename);
                            //文件大小
                            jo.put("size", size);
                            //随意，代表的是鼠标经过图片时显示的文字
                            jo.put("title", infoList[1]);
                            //文件后缀名
                            //这里的url字段表示的是上传后的图片在图片服务器的完整地址（http://ip:端口/***/***/***.jpg）
                            jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename()));
                            jo.put("url", infoList[2]);
                            //如果上传失败
                        }else{

                        }
                        ResponseUtils.renderJson(response, jo.toString());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
